package com.gonsin.gview.logic.parser;

import com.gonsin.gview.annotations.GContext;
import com.gonsin.gview.annotations.GView;
import com.gonsin.gview.annotations.GViews;
import com.gonsin.gview.annotations.board.GBoard;
import com.gonsin.gview.annotations.board.GButton;
import com.gonsin.gview.annotations.board.form.*;
import com.gonsin.gview.annotations.board.tab.GTab;
import com.gonsin.gview.annotations.board.table.*;
import com.gonsin.gview.annotations.data.*;
import com.gonsin.gview.annotations.enums.EnumsType;
import com.gonsin.gview.annotations.impl.*;
import com.gonsin.gview.annotations.interfaces.*;
import com.gonsin.gview.annotations.model.DownloadResponse;
import com.gonsin.gview.annotations.model.ViewRequest;
import com.gonsin.gview.logic.GViewEnvironment;
import com.gonsin.gview.logic.exceptions.BaseGViewException;
import com.gonsin.gview.logic.model.ActionPo;
import com.gonsin.gview.logic.model.ClassView;
import com.gonsin.gview.logic.model.DataSourcePo;
import com.gonsin.gview.logic.model.GFutureBoardModel;
import com.gonsin.gview.logic.services.*;
import com.gonsin.gview.model.*;
import com.gonsin.gview.model.data.*;
import com.gonsin.gview.model.form.*;
import com.gonsin.gview.model.struct.EnumItem;
import com.gonsin.gview.model.tab.GLinkBoardModel;
import com.gonsin.gview.model.tab.GTabModel;
import com.gonsin.gview.model.tab.GTabModels;
import com.gonsin.gview.model.table.*;
import com.gonsin.i18n.logic.T;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.ClassUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * View转换器
 */
@Slf4j
@Component
@Qualifier("StanderParser")
public class StanderParser implements IGViewParser<ClassView>{


    @Autowired private GViewDataServiceImpl dataService;
    @Autowired private GViewActionServiceImpl actionService;
    @Autowired private GViewGlobalEnumsServiceImpl globalEnumsService;
    @Autowired private GViewCoreServiceImpl coreService;
//    @Autowired private GViewFutureBindingService bindingService;

    @Autowired(required = false) IViewPermissionHandler permissionHandler;

    /**
     * 解析动态GView
     *
     * @param context
     * @return
     */
    @Override
    public GViewModel parse(GContext context, ClassView classView) {
        GViewModel model = new GViewModel();
        model.setViewName(context.getViewName());
        model.setTitle(classView.getView().title());
        model.setProps(Arrays.asList(classView.getView().props()));
        model.setBoards(new ArrayList<>());
        model.setContext(context);


        if(ArrayUtils.isNotEmpty(classView.getView().boards())){
            for (GBoard view : classView.getView().boards()){

                // 如果是表单view
                if(view.form().enable()){
                    GFormBoardModel formModel = initFormView(context, view.form());
                    model.getBoards().add(formModel);

                    // 如果是列表view
                } else if(view.table().enable()){
                    GTableBoardModel tableView = initTableBoard(context, view.table());
                    model.getBoards().add(tableView);

                } else if(view.tab().length > 0){
                    GTabModels tabs = initTabBoards(context, view.tab());
                    model.getBoards().add(tabs);
                }
            }
        }

        if(GViewEnvironment.LOG){
            log.info("已完成，view = {}", model.getViewName());
        }
        return model;
    }


    /**
     * 初始化多个tab
     */
    private GTabModels initTabBoards(GContext context, GTab[] tab) {

        GTabModels models = new GTabModels();
        models.setBoardType("tab");
        models.setTabs(new ArrayList<>());
        for(int i = 0; i < tab.length; i++){
            GTab t = tab[i];
            GTabModel m = new GTabModel();
            m.setTitle(t.title());
            m.setProps(Arrays.asList(t.props()));
            if(t.form().enable() || t.table().enable()){
                m.setBoard(initTabBoard(context, t));
            } else if(StringUtils.isNotEmpty(t.viewName())) {
                if(!context.isInitialing()){
                    IViewModelHolder v = coreService.findViewByName(t.viewName());
                    GViewModel model = v.getViewModel(new ViewRequest(context.getRequest(), context.getResponse(), context.getProps()), permissionHandler);
                    m.setBoard(model.getBoards().get(0));
                }
//                bindingService.addAfterView(new Runnable() {
//                    @Override
//                    public void run() {
//
//                        // TODO 只支持静态的GView绑定
//                        IViewModelHolder v = coreService.findViewByName(t.viewName());
//                        if(v instanceof StanderModelHolder){
//
//                            return;
//                        }
//                        throw new BaseGViewException("当前版本不支持在@GTab中绑定 @GDynamicView 的view");
//
//                    }
//                });
            } else if(StringUtils.isNotEmpty(t.link())){
                m.setBoard(initLinkBoard(context, t.link()));
            } else {
                throw new BaseGViewException(String.format("【%s】中的@GTab必须设置@GForm、@GTable、viewName、link其中之一", context.getViewName()));
            }
            models.getTabs().add(m);
        }
        return models;
    }

    private GBoardModel initFutureBoard(GContext context, String viewName) {
        GFutureBoardModel boardModel = new GFutureBoardModel();
        boardModel.setViewName(viewName);
        return boardModel;
    }

    /**
     * 初始化一个link板块
     */
    private GBoardModel initLinkBoard(GContext context, String link) {
        GLinkBoardModel boardModel = new GLinkBoardModel();
        boardModel.setLink(link);
        return boardModel;
    }

    /**
     * 初始化@GTab
     */
    private GBoardModel initTabBoard(GContext context, GTab t) {
        // 如果是表单view
        if(t.form().enable()){
            return initFormView(context, t.form());

            // 如果是列表view
        } else if(t.table().enable()) {
            return initTableBoard(context, t.table());
        }

        return null;
    }


    /**
     * 初始化列表页
     */
    private GTableBoardModel initTableBoard(GContext context, GTable table) {
        GTableBoardModel model = new GTableBoardModel();

        model.setBoardType("table");
        model.setCount(table.count());
        model.setItemName(table.itemName());

        GHeaderModel header = new GHeaderModel();
        GHeader gHeader = table.header();
        header.setButtons(new ArrayList<>());
        for(GButton button : gHeader.buttons()){
            GButtonModel buttonModel = initButton(context, button);
            if(buttonModel == null){
                continue;
            }
            header.getButtons().add(buttonModel);
        }

        if(gHeader.searchBar().enable()){
            GSearchBarModel searchBar = new GSearchBarModel();
            header.setSearchBar(searchBar);
            searchBar.setFilters(new ArrayList<>());
            GSearchBar gSearchBar = gHeader.searchBar();
            for(GSearchFilter gSearchFilter : gSearchBar.filters()){

                // 下拉选择框
                if(gSearchFilter.selector().enable()){
                    GSelectorModel selector = initSelector(context, gSearchFilter.selector());
                    searchBar.getFilters().add(selector);
                }

                // 时间选择框
                if(gSearchFilter.timeSelector().enable()){
                    GTimeSelectorModel selector = initTimeSelector(context, gSearchFilter.timeSelector());
                    searchBar.getFilters().add(selector);
                }

                // 时间选择框
                if(gSearchFilter.delaySelector().enable()){
                    GDelaySelectorModel selector = initDelaySelector(context, gSearchFilter.delaySelector());
                    searchBar.getFilters().add(selector);
                }

                // 日期选择框
                if(gSearchFilter.dateTimeSelector().enable()){
                    GDateTimeSelectorModel selector = initDateTimeSelector(context, gSearchFilter.dateTimeSelector());
                    searchBar.getFilters().add(selector);
                }

                // 日期时间选择框
                if(gSearchFilter.dateSelector().enable()){
                    GDateSelectorModel selector = initDateSelector(context, gSearchFilter.dateSelector());
                    searchBar.getFilters().add(selector);
                }

                // 文本框
                if(gSearchFilter.textInput().enable()){
                    GTextInputModel textInput = initTextInput(context, gSearchFilter.textInput());
                    searchBar.getFilters().add(textInput);
                }
            }
        }
        model.setHeader(header);

        //
        GTableDataModel dataModel = initTableData(context, table.tableData());
        model.setTableData(dataModel);


        //
        model.setColumns(new ArrayList<>());
        for(GColumn column : table.columns()){

            GColumnModel columnModel = initColumn(context, column);
            model.getColumns().add(columnModel);

        }
        return model;
    }

    /**
     * 初始化时间选择器
     */
    private GTimeSelectorModel initTimeSelector(GContext context, GTimeSelector timeSelector) {
        GTimeSelectorModel selectorModel = new GTimeSelectorModel();
        selectorModel.setName(timeSelector.name());
        selectorModel.setItemType("time_selector");
        selectorModel.setKeyName(timeSelector.keyName());
        selectorModel.setRequired(timeSelector.required());
        selectorModel.setPlaceholder(timeSelector.placeholder());
        selectorModel.setShowIf(timeSelector.showIf());
        selectorModel.setDisableIf(timeSelector.disableIf());
//        selectorModel.setOnChangeAction(timeSelector.onChangeAction());
//        checkExistAction(context,  timeSelector.onChangeAction());

        if(StringUtils.isNotEmpty(timeSelector.onChangeAction())){
            selectorModel.setButtonId(IdUtils.nextButtonId(timeSelector.onChangeAction()));
            // 设置对应的actionName
            String actionName = timeSelector.onChangeAction();
            ActionPo action = coreService.findActionByName(actionName);
            if(action == null){
                throw new BaseGViewException(String.format("【%s】里面的设了onChangeAction=%s，但是没有找到对应的actionName"
                        , context.getViewName(), actionName));
//                        throw new ActionNotFoundException(context, actionName);
            }
            actionService.putConfirmAction(context, selectorModel.getButtonId(),
                    action.getActionService(), action.getActionMethod());
        }
        return selectorModel;
    }

    /**
     * 初始化时间选择器
     */
    private GDelaySelectorModel initDelaySelector(GContext context, GDelaySelector timeSelector) {
        GDelaySelectorModel selectorModel = new GDelaySelectorModel();
        selectorModel.setName(timeSelector.name());
        selectorModel.setItemType("delay_selector");
        selectorModel.setKeyName(timeSelector.keyName());
        selectorModel.setRequired(timeSelector.required());
        selectorModel.setPlaceholder(timeSelector.placeholder());
        selectorModel.setShowIf(timeSelector.showIf());
        selectorModel.setDisableIf(timeSelector.disableIf());
//        selectorModel.setOnChangeAction(timeSelector.onChangeAction());
//        checkExistAction(context,  timeSelector.onChangeAction());

        if(StringUtils.isNotEmpty(timeSelector.onChangeAction())){
            selectorModel.setButtonId(IdUtils.nextButtonId(timeSelector.onChangeAction()));
            // 设置对应的actionName
            String actionName = timeSelector.onChangeAction();
            ActionPo action = coreService.findActionByName(actionName);
            if(action == null){
                throw new BaseGViewException(String.format("【%s】里面的设了onChangeAction=%s，但是没有找到对应的actionName"
                        , context.getViewName(), actionName));
//                        throw new ActionNotFoundException(context, actionName);
            }
            actionService.putConfirmAction(context, selectorModel.getButtonId(),
                    action.getActionService(), action.getActionMethod());
        }
        return selectorModel;
    }

    /**
     * 初始化时间选择器
     */
    private GTagModel initTag(GContext context, GTag tag) {
        GTagModel selectorModel = new GTagModel();
        selectorModel.setName(tag.name());
        selectorModel.setItemType("tag");
        selectorModel.setKeyName(tag.keyName());
        selectorModel.setRequired(tag.required());
        selectorModel.setPlaceholder(tag.placeholder());
        selectorModel.setShowIf(tag.showIf());
        selectorModel.setDisableIf(tag.disableIf());
//        selectorModel.setOnChangeAction(timeSelector.onChangeAction());
//        checkExistAction(context,  timeSelector.onChangeAction());

        if(StringUtils.isNotEmpty(tag.onChangeAction())){
            selectorModel.setButtonId(IdUtils.nextButtonId(tag.onChangeAction()));
            // 设置对应的actionName
            String actionName = tag.onChangeAction();
            ActionPo action = coreService.findActionByName(actionName);
            if(action == null){
                throw new BaseGViewException(String.format("【%s】里面的设了onChangeAction=%s，但是没有找到对应的actionName"
                        , context.getViewName(), actionName));
//                        throw new ActionNotFoundException(context, actionName);
            }
            actionService.putConfirmAction(context, selectorModel.getButtonId(),
                    action.getActionService(), action.getActionMethod());
        }
        return selectorModel;
    }

    /**
     * 初始化日期选择器
     */
    private GDateSelectorModel initDateSelector(GContext context, GDateSelector timeSelector) {
        GDateSelectorModel selectorModel = new GDateSelectorModel();
        selectorModel.setName(timeSelector.name());
        selectorModel.setKeyName(timeSelector.keyName());
        selectorModel.setPlaceholder(timeSelector.placeholder());
        selectorModel.setRequired(timeSelector.required());
        selectorModel.setShowIf(timeSelector.showIf());
        selectorModel.setDisableIf(timeSelector.disableIf());
//        selectorModel.setOnChangeAction(timeSelector.onChangeAction());
//        checkExistAction(context,  timeSelector.onChangeAction());


        if(StringUtils.isNotEmpty(timeSelector.onChangeAction())){
            selectorModel.setButtonId(IdUtils.nextButtonId(timeSelector.onChangeAction()));
            // 设置对应的actionName
            String actionName = timeSelector.onChangeAction();
            ActionPo action = coreService.findActionByName(actionName);
            if(action == null){
                throw new BaseGViewException(String.format("【%s】里面的设了onChangeAction=%s，但是没有找到对应的actionName"
                        , context.getViewName(), actionName));
//                        throw new ActionNotFoundException(context, actionName);
            }
            actionService.putConfirmAction(context, selectorModel.getButtonId(),
                    action.getActionService(), action.getActionMethod());
        }
        return selectorModel;
    }

    /**
     * 初始化日期时间选择器
     */
    private GDateTimeSelectorModel initDateTimeSelector(GContext context, GDateTimeSelector timeSelector) {
        GDateTimeSelectorModel selectorModel = new GDateTimeSelectorModel();
        selectorModel.setName(timeSelector.name());
        selectorModel.setKeyName(timeSelector.keyName());
        selectorModel.setPlaceholder(timeSelector.placeholder());
        selectorModel.setRequired(timeSelector.required());
        selectorModel.setShowIf(timeSelector.showIf());
        selectorModel.setDisableIf(timeSelector.disableIf());
//        selectorModel.setOnChangeAction(timeSelector.onChangeAction());
//        checkExistAction(context,  timeSelector.onChangeAction());

        if(StringUtils.isNotEmpty(timeSelector.onChangeAction())){
            selectorModel.setButtonId(IdUtils.nextButtonId(timeSelector.onChangeAction()));
            // 设置对应的actionName
            String actionName = timeSelector.onChangeAction();
            ActionPo action = coreService.findActionByName(actionName);
            if(action == null){
                throw new BaseGViewException(String.format("【%s】里面的设了onChangeAction=%s，但是没有找到对应的actionName"
                        , context.getViewName(), actionName));
//                        throw new ActionNotFoundException(context, actionName);
            }
            actionService.putConfirmAction(context, selectorModel.getButtonId(),
                    action.getActionService(), action.getActionMethod());
        }
        return selectorModel;
    }

    private GColumnModel initColumn(GContext context, GColumn column) {
        GColumnModel columnModel = new GColumnModel();
        columnModel.setColumnType(column.columnType().name());
        columnModel.setButtons(new ArrayList<>());
        columnModel.setFormItems(new ArrayList<>());
        for(GButton button : column.buttons()){
            GButtonModel buttonModel = initButton(context, button);
            if(buttonModel == null){
                continue;
            }
            columnModel.getButtons().add(buttonModel);
        }
        for(GFormItem item : column.formItems()){
            GFormItemModel itemModel = initFormItem(context, item);
            if(itemModel == null){
                continue;
            }
            columnModel.getFormItems().add(itemModel);
        }
        columnModel.setFormat(column.format());
        columnModel.setName(column.name());
        columnModel.setKeyName(column.keyName());
        columnModel.setValue(column.value());
        columnModel.setWeight(column.weight());


        switch(column.columnType()){
            case TEXT:
                break;
            case BUTTONS:
                if(column.buttons().length == 0){
                    log.warn("按钮类型的column没有一个按钮");
                }
                break;
            case ENUMS:
                if(column.enums().length > 0) {
                    columnModel.setEnums(initEnums(context, column.enums()));
                } else if(column.enumName().length() > 0){
                    columnModel.setEnums(initEnumByName(context, column.enumName()));
                } else {
                    throw new BaseGViewException(String.format("【%s】里面的某个@GColumn设了columnType=ENUMS，但是没有设置enums 或 enumName"
                            , context.getViewName()));
                }
        }

        return columnModel;
    }

    private List<GEnumsModel> initEnumByName(GContext context, String enumName) {
        List<EnumItem> items = globalEnumsService.getEnums(enumName);
        if(items == null){
            throw new BaseGViewException(String.format("【%s】里面的某个@GColumn设了enumName=\"%s\"，但是没有找到【%s】"
                    , context.getViewName(), enumName, enumName));
        }
        List<GEnumsModel> result = new ArrayList<>();
        for(EnumItem e : items){
            GEnumsModel model = new GEnumsModel();
            model.setValue(e.getValue().toString());
            model.setType(EnumsType.TEXT.name());
            model.setText(T.t(e.getTitle()));
            result.add(model);
        }
        return result;
    }


    private List<GEnumsModel> initEnums(GContext context, GEnum[] enums){
        List<GEnumsModel> result = new ArrayList<>();
        for(GEnum e : enums){
            GEnumsModel model = new GEnumsModel();
            model.setValue(e.value());
            model.setType(e.type().name());
            model.setIconUrl(e.iconUrl());
            model.setIconSize(e.iconSize());
            if(StringUtils.isNotEmpty(e.text())){
                model.setText(T.t(e.text()));
            } else {
                model.setText(e.text());
            }
            result.add(model);
        }
        return result;
    }

    private GButtonModel initButton(GContext context, GButton button) {
        GButtonModel buttonModel = new GButtonModel();
//        buttonModel.setButtonId(RandomStringUtils.random(32, true, true));
        buttonModel.setButtonStyle(button.buttonStyle().name());
        buttonModel.setButtonType(button.buttonType().name());
        buttonModel.setAction(button.action().name());
        buttonModel.setName(button.name());
//        buttonModel.setDialogBoard(button.viewDialog());
        buttonModel.setIcon(button.icon());
        buttonModel.setLink(button.link());
        buttonModel.setView(button.view());
//        buttonModel.setTarget(button.target());
        buttonModel.setDownloadUrl(button.downloadUrl());
        buttonModel.setTextColor(button.textColor());
        buttonModel.setShowIf(button.showIf());
        buttonModel.setDisableIf(button.disableIf());
        buttonModel.setConfirmMessage(button.confirmMessage());
        buttonModel.setContext(context);
        buttonModel.setFileUploadType(button.fileUploadType());
        buttonModel.setOutLink(button.outLink());
        buttonModel.setPermission(button.permission());


        // 2024/06/24 新增，用于判断按钮的权限确定是否显示
        if(button.permission() != null && button.permission().length > 0){
            if(permissionHandler != null){
                if(!permissionHandler.handPermissions(context, button.permission(), buttonModel)){
                    return null;
                }
            }
        }

        switch(button.action()){
            case LINK:
                if(StringUtils.isEmpty(buttonModel.getLink())){
                    throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=link但是没有设置link"
                            , context.getViewName()));
                }
                buttonModel.setProps(initProps(button.props()));
                break;
            case VIEW:
            case VIEW_BY_DIALOG:
                if(StringUtils.isEmpty(buttonModel.getView()) && StringUtils.isEmpty(buttonModel.getLink())){
//                    throw new PageNotFoundException();
                    throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=【%s】但是没有设置view"
                            , context.getViewName(), button.action()));
                }

                if(!context.isInitialing()){
                    if(coreService.findViewByName(buttonModel.getView()) == null){
                        throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=【%s】但是没有找不到该view"
                                , context.getViewName(), button.action()));
                    }
                    coreService.putViewButton(buttonModel.getView(), buttonModel);
                }


//                bindingService.addAfterView(new Runnable() {
//                    @Override
//                    public void run() {
//                        if(!StringUtils.isEmpty(buttonModel.getView())){
//                            if(coreService.findViewByName(buttonModel.getView()) == null){
//                                throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=【%s】但是没有找不到该view"
//                                        , context.getViewName(), button.action()));
//                            }
//                            coreService.putViewButton(buttonModel.getView(), buttonModel);
//                        }
//                    }
//                });
                buttonModel.setProps(initProps(button.props()));
                break;
            case UPLOAD_FILE:
                buttonModel.setButtonId(IdUtils.nextButtonId());
                if(button.fileAction() != EmptyFileActionImpl.class){
                    actionService.putFileAction(context, buttonModel.getButtonId(), button.fileAction());
                } else if(!StringUtils.isEmpty(button.fileActionClass())){
                    try {
                        Class<? extends IFileActionListener> clazz =
                                (Class<? extends IFileActionListener>) ClassUtils.getClass(button.fileActionClass());
                        actionService.putFileAction(context, buttonModel.getButtonId(), clazz);
                    } catch (ClassNotFoundException e) {
                        log.error(e.toString(), e);
                        throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=upload_file但是没有找到对应的class【%s】"
                                , context.getViewName(), button.fileActionClass()));
//                        throw new ActionClassNotFoundException(context, button.fileActionClass());
                    }
                } else if(!StringUtils.isEmpty(button.actionName())){
                    String actionName = button.actionName();
                    buttonModel.setButtonId(IdUtils.nextButtonId(actionName));
                     ActionPo action = coreService.findActionByName(actionName);
                    if(action == null){
                        throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=upload_file但是没有找到对应的actionName【%s】"
                                , context.getViewName(), button.actionName()));
//                        throw new ActionNotFoundException(context, actionName);
                    }
                    actionService.putFileAction(context, buttonModel.getButtonId(), button.actionName(),
                            action.getActionService(), action.getActionMethod());
                } else {
                    throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=upload_file但是没有设上传事件"
                            , context.getViewName()));
                }
                buttonModel.setLimit(button.limit());
                buttonModel.setAccept(button.accept());
                buttonModel.setShowIf(button.showIf());
                buttonModel.setDisableIf(button.disableIf());
                buttonModel.setProps(initProps(button.props()));
                break;
            case DOWNLOAD:
                buttonModel.setProps(initProps(button.props()));
                if(StringUtils.isEmpty(button.actionName())){
                    if(StringUtils.isEmpty(buttonModel.getDownloadUrl())){
                        throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=download但是没有设downloadUrl"
                                , context.getViewName()));
                    }
                    buttonModel.setProps(initProps(button.props()));
                } else {
                    String actionName = button.actionName();
                    buttonModel.setButtonId(IdUtils.nextButtonId(actionName));
                    ActionPo action = coreService.findActionByName(actionName);
                    if(action == null){
                        throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action = download 但是没有找到对应的actionName【%s】"
                                , context.getViewName(), button.actionName()));
//                        throw new ActionNotFoundException(context, actionName);
                    }
                    if(!DownloadResponse.class.equals(action.getReturnType())){
                        throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action = download 但是找到对应的actionName【%s】 返回类型不是 DownloadResponse "
                                , context.getViewName(), button.actionName()));
                    }
                    actionService.putDownloadAction(context, buttonModel.getButtonId(), button.actionName(),
                            action.getActionService(), action.getActionMethod());
//                    buttonModel.setDownloadUrl("/restapi/s09/gview/active/download?viewName=" + context.getViewName() + "&buttonId=" + buttonModel.getButtonId());
                }
                break;
//            case VIEW_BY_DIALOG:
//                if(StringUtils.isEmpty(buttonModel.getView())){
//                    throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=view_by_dialog,但是没有设view"
//                            , context.getViewName()));
//                }
//                buttonModel.setProps(initProps(button.props()));
////                if(!boardNameList.contains(buttonModel.getView())){
////                    throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=view_by_dialog,但是没有找到对应的view【%s】"
////                            , context.getViewName(), buttonModel.getView()));
////                }
//                buttonModel.setProps(initProps(button.props()));
//                break;
            case CLOSE_DIALOG:
                break;

            case BATCH:
                buttonModel.setButtonId(IdUtils.nextButtonId());
                if(button.batchAction() != EmptyBatchActionImpl.class){
                    actionService.putBatchAction(context, buttonModel.getButtonId(), button.batchAction());
                } else if(!StringUtils.isEmpty(button.batchActionClass())){
                    try {
                        Class<? extends IBatchActionListener> clazz =
                                (Class<? extends IBatchActionListener>) ClassUtils.getClass(button.batchActionClass());
                        actionService.putBatchAction(context, buttonModel.getButtonId(), clazz);
                    } catch (ClassNotFoundException e) {
                        log.error(e.toString(), e);
                        throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=batch，但是但是找不到该类【%s】"
                                , context.getViewName(), button.batchActionClass()));
                    }
                } else if(!StringUtils.isEmpty(button.actionName())){
                    String actionName = button.actionName();
                    buttonModel.setButtonId(IdUtils.nextButtonId(actionName));
                     ActionPo action = coreService.findActionByName(actionName);
                    if(action == null){
                        throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=batch,但是没有找到对应的actionName【%s】"
                                , context.getViewName(), button.actionName()));
//                        throw new ActionNotFoundException(context, actionName);
                    }
                    actionService.putBatchAction(context, buttonModel.getButtonId(), action.getActionService(), action.getActionMethod());
                } else {
//                    throw new ActionNotSetException(context);
                    throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=batch,但是没有设置点击事件"
                            , context.getViewName()));
                }
                buttonModel.setProps(initProps(button.props()));
                break;

            // TODO 表单方式的提交

            case CONFIRM:
            case CONFIRM_AND_CLOSE:
                buttonModel.setButtonId(IdUtils.nextButtonId());
                if(button.confirmAction() != EmptyConfirmActionImpl.class){
                    actionService.putConfirmAction(context, buttonModel.getButtonId(), button.confirmAction());
                } else if(!StringUtils.isEmpty(button.confirmActionClass())){
                    try {
                        Class<? extends IConfirmActionListener> clazz =
                                (Class<? extends IConfirmActionListener>) ClassUtils.getClass(button.confirmActionClass());
                        actionService.putConfirmAction(context, buttonModel.getButtonId(), clazz);
                    } catch (ClassNotFoundException e) {
                        log.error(e.toString(), e);
                        throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=confirm 或 action=confirm_and_close 但是没有找到class【%s】"
                                , context.getViewName(), button.confirmActionClass()));
                    }
                } else if(!StringUtils.isEmpty(button.actionName())){
                    String actionName = button.actionName();
                    buttonModel.setButtonId(IdUtils.nextButtonId(actionName));
                     ActionPo action = coreService.findActionByName(actionName);
                    if(action == null){
                        throw new BaseGViewException(String.format("【%s】里面的某个按钮设了action=confirm 或 action=confirm_and_close 但是没有找到actionName【%s】"
                                , context.getViewName(), button.actionName()));
                    }
                    actionService.putConfirmAction(context, buttonModel.getButtonId(), action.getActionService(), action.getActionMethod());
                } else {
                    throw new BaseGViewException(String.format("【%s】页面的某个按钮设了confirm但是没有设点击事件", context.getViewName()));
                }
                buttonModel.setProps(initProps(button.props()));
                break;

        }

        return buttonModel;
    }

    private List<GPropModel> initProps(GProp[] props) {
        List<GPropModel> propModels = new ArrayList<>();
        for(GProp prop : props){
            GPropModel model = new GPropModel();
            model.setValueName(prop.valueName());
            model.setKeyName(prop.keyName());
            propModels.add(model);

            // TODO  检测props是否有效
        }
        return propModels;
    }

    private GTextInputModel initTextInput(GContext context, GTextInput textInput) {
        GTextInputModel textInputModel = new GTextInputModel();
        textInputModel.setInputType(textInput.inputType().name());
        textInputModel.setName(textInput.name());
        textInputModel.setKeyName(textInput.keyName());
        textInputModel.setPlaceholder(textInput.placeholder());
        textInputModel.setRequired(textInput.required());
        textInputModel.setRegular(textInput.regular());
        textInputModel.setRegularMessage(textInput.regularMessage());
        textInputModel.setShowIf(textInput.showIf());
        textInputModel.setDisableIf(textInput.disableIf());
//        textInputModel.setOnChangeAction(textInput.onChangeAction());
//        checkExistAction(context,  textInput.onChangeAction());

        if(StringUtils.isNotEmpty(textInput.onChangeAction())){
            textInputModel.setButtonId(IdUtils.nextButtonId(textInput.onChangeAction()));
            // 设置对应的actionName
            String actionName = textInput.onChangeAction();
            ActionPo action = coreService.findActionByName(actionName);
            if(action == null){
                throw new BaseGViewException(String.format("【%s】里面的设了onChangeAction=%s，但是没有找到对应的actionName"
                        , context.getViewName(), actionName));
//                        throw new ActionNotFoundException(context, actionName);
            }
            actionService.putConfirmAction(context, textInputModel.getButtonId(),
                    action.getActionService(), action.getActionMethod());
        }
        if(textInput.simpleListData().enable()){
            textInputModel.setSimpleListData(initSimpleListData(context, textInput.simpleListData()));
        }
        return textInputModel;
    }


    private GFormItemModel initFormItem(GContext context, GFormItem item){
        // 隐藏数据
        if(item.hidden().enable()){
            return initHidden(item.hidden());

            // 多选下拉框
        } else if(item.multiSelector().enable()){
            return initMultiSelector(context, item.multiSelector());

            // 树状多选下拉框
        } else if(item.multiTreeSelector().enable()){
            return initMultiTreeSelector(context, item.multiTreeSelector());

            // 复选框
        } else if(item.checkBox().enable()){
            return initCheckBox(context, item.checkBox());

            // switch滑块
        } else if(item.gswitch().enable()){
            return initSwitch(context, item.gswitch());

            // 文件上传框
        } else if(item.file().enable()){
            return initFile(item.file());

            // 单选框
        } else if(item.radio().enable()){
            return initRadio(context, item.radio());

            // 富文本框
        } else if(item.richText().enable()){
            return initRichText(item.richText());

            // 下拉框
        } else if(item.selector().enable()){
            return initSelector(context, item.selector());

            // 文本框
        } else if(item.textInput().enable()){
            return initTextInput(context, item.textInput());

            // 树状复选框
        } else if(item.treeCheckBox().enable()){
            return initTreeCheckBox(context, item.treeCheckBox());

            // 树状选择框
        } else if(item.treeSelector().enable()){
            return initTreeSelector(context, item.treeSelector());

            // 静态文本框
        } else if(item.label().enable()) {
            return initLabel(context, item.label());

            // 时间选择器
        } else if(item.image().enable()) {
            return initImage(context, item.image());

            // 时间选择器
        }else if(item.timeSelector().enable()){
            return initTimeSelector(context, item.timeSelector());

            // 日期选择器
        }else if(item.delaySelector().enable()){
            return initDelaySelector(context, item.delaySelector());

            // 日期选择器
        }else if(item.tag().enable()){
            return initTag(context, item.tag());

            // 日期选择器
        }else if(item.dateSelector().enable()){
            return initDateSelector(context, item.dateSelector());

            // 日期时间选择器
        }else if(item.dateTimeSelector().enable()){
            return initDateTimeSelector(context, item.dateTimeSelector());

            // 分隔线
        }else if(item.line().enable()){
            return initLine(context, item.line());
        }else if(item.blockStart().enable()){
            return initBlockStart(context, item.blockStart());
        }else if(item.blockEnd().enable()){
            return initBlockEnd(context, item.blockEnd());
        }

        throw new BaseGViewException(String.format("在【%s】中，无法识别标签类型【%s】", context.getViewName(), item.toString()));
    }

    private GFormItemModel initBlockStart(GContext context, GBlockStart blockStart) {
        GBlockStartModel model = new GBlockStartModel();
        model.setItemType("block_start");
        model.setShowIf(blockStart.showIf());
        model.setName(blockStart.name());
        return model;
    }

    private GFormItemModel initBlockEnd(GContext context, GBlockEnd blockEnd) {
        GBlockEndModel model = new GBlockEndModel();
        model.setItemType("block_end");
        model.setShowIf(blockEnd.showIf());
        model.setName(blockEnd.name());
        return model;
    }

    /**
     * 初始化表单页
     */
    private GFormBoardModel initFormView(GContext context, GForm form) {
        GFormBoardModel model = new GFormBoardModel();
        model.setBoardType("form");
        if(form.cancelButton().enable()){
            GButtonModel buttonModel = initButton(context, form.cancelButton());
            if(buttonModel != null){
                model.setCancelButton(buttonModel);
            }
        }
        if(form.okButton().enable()){
            GButtonModel buttonModel = initButton(context, form.okButton());
            if(buttonModel != null){
                if(StringUtils.isEmpty(buttonModel.getName())){
                    buttonModel.setName("确定");
                }
                model.setOkButton(buttonModel);
            }
        }
        model.setFormItems(new ArrayList<>());
        if(form.data().enable()){
            model.setData(initData(context, form.data()));
        }
        for(GFormItem item : form.formItems()){
            GFormItemModel itemModel = initFormItem(context, item);
            if(itemModel == null){
                continue;
            }
            model.getFormItems().add(itemModel);
        }
        return model;
    }


    /**
     * 初始化分割线
     */
    private GLineModel initLine(GContext context, GLine line) {
        GLineModel model = new GLineModel();
        model.setItemType("line");
        model.setName(line.name());
        model.setShowIf(line.showIf());
        return model;
    }


    /**
     * 初始化静态文本框
     */
    private GLabelModel initLabel(GContext context, GLabel label) {
        GLabelModel model = new GLabelModel();
        model.setItemType("label");
        model.setKeyName(label.keyName());
        model.setName(label.name());
        model.setValue(label.value());
        model.setShowIf(label.showIf());
        return model;
    }


    /**
     * 初始化静态文本框
     */
    private GImageModel initImage(GContext context, GImage image) {
        GImageModel model = new GImageModel();
        model.setItemType("image");
        model.setKeyName(image.keyName());
        model.setName(image.name());
        model.setValue(image.value());
        model.setShowIf(image.showIf());
        return model;
    }

    private GTreeSelectorModel initTreeSelector(GContext context, GTreeSelector selector) {
        GTreeSelectorModel radioModel = new GTreeSelectorModel();
        radioModel.setName(selector.name());
        radioModel.setKeyName(selector.keyName());
        radioModel.setRequired(selector.required());
        radioModel.setShowIf(selector.showIf());
        radioModel.setDisableIf(selector.disableIf());
//        radioModel.setOnChangeAction(selector.onChangeAction());
//        checkExistAction(context,  selector.onChangeAction());

        if(StringUtils.isNotEmpty(selector.onChangeAction())){
            radioModel.setButtonId(IdUtils.nextButtonId(selector.onChangeAction()));
            // 设置对应的actionName
            String actionName = selector.onChangeAction();
            ActionPo action = coreService.findActionByName(actionName);
            if(action == null){
                throw new BaseGViewException(String.format("【%s】里面的设了onChangeAction=%s，但是没有找到对应的actionName"
                        , context.getViewName(), actionName));
//                        throw new ActionNotFoundException(context, actionName);
            }
            actionService.putConfirmAction(context, radioModel.getButtonId(),
                    action.getActionService(), action.getActionMethod());
        }


        GTreeData treeData = selector.treeData();
        if(!treeData.enable()){
//            throw new DynamicDataNotSetException();
            throw new BaseGViewException(String.format("页面【%s】的 @GTreeCheckBox 没有设 treeData ",
                    context.getViewName()));
        }

        GTreeDataModel dataModel = initTreeSelectorData(context, treeData);
        radioModel.setTreeData(dataModel);

        return radioModel;
    }

    private GTreeCheckBoxModel initTreeCheckBox(GContext context, GTreeCheckBox treeCheckBox) {
        GTreeCheckBoxModel radioModel = new GTreeCheckBoxModel();
        radioModel.setName(treeCheckBox.name());
        radioModel.setKeyName(treeCheckBox.keyName());
        radioModel.setRequired(treeCheckBox.required());
        radioModel.setShowIf(treeCheckBox.showIf());
        radioModel.setDisableIf(treeCheckBox.disableIf());
//        radioModel.setOnChangeAction(treeCheckBox.onChangeAction());
//        checkExistAction(context,  treeCheckBox.onChangeAction());


        if(StringUtils.isNotEmpty(treeCheckBox.onChangeAction())){
            radioModel.setButtonId(IdUtils.nextButtonId(treeCheckBox.onChangeAction()));
            // 设置对应的actionName
            String actionName = treeCheckBox.onChangeAction();
            ActionPo action = coreService.findActionByName(actionName);
            if(action == null){
                throw new BaseGViewException(String.format("【%s】里面的设了onChangeAction=%s，但是没有找到对应的actionName"
                        , context.getViewName(), actionName));
//                        throw new ActionNotFoundException(context, actionName);
            }
            actionService.putConfirmAction(context, radioModel.getButtonId(),
                    action.getActionService(), action.getActionMethod());
        }


        GTreeData treeData = treeCheckBox.treeData();
        if(!treeData.enable()){
//            throw new DynamicDataNotSetException();
            throw new BaseGViewException(String.format("页面【%s】的 @GTreeCheckBox 没有设 treeData ",
                    context.getViewName()));
        }

        GTreeDataModel dataModel = initTreeSelectorData(context, treeData);
        radioModel.setTreeData(dataModel);

        return radioModel;
    }

    private GRichTextModel initRichText(GRichText richText) {
        GRichTextModel textModel = new GRichTextModel();
        textModel.setColumn(richText.column());
        textModel.setKeyName(richText.keyName());
        textModel.setName(richText.name());
        textModel.setRequired(richText.required());
        textModel.setShowIf(richText.showIf());
        textModel.setDisableIf(richText.disableIf());
        return textModel;
    }

    private GFormItemModel initRadio(GContext context, GRadio radio) {
        GRadioModel radioModel = new GRadioModel();
        radioModel.setName(radio.name());
        radioModel.setKeyName(radio.keyName());
        radioModel.setRequired(radio.required());
        radioModel.setPlaceholder(radio.placeholder());
        radioModel.setShowIf(radio.showIf());
        radioModel.setDisableIf(radio.disableIf());
//        radioModel.setOnChangeAction(radio.onChangeAction());
//        checkExistAction(context,  radio.onChangeAction());

        if(StringUtils.isNotEmpty(radio.onChangeAction())){
            radioModel.setButtonId(IdUtils.nextButtonId(radio.onChangeAction()));
            // 设置对应的actionName
            String actionName = radio.onChangeAction();
            ActionPo action = coreService.findActionByName(actionName);
            if(action == null){
                throw new BaseGViewException(String.format("【%s】里面的设了onChangeAction=%s，但是没有找到对应的actionName"
                        , context.getViewName(), actionName));
//                        throw new ActionNotFoundException(context, actionName);
            }
            actionService.putConfirmAction(context, radioModel.getButtonId(),
                    action.getActionService(), action.getActionMethod());
        }


        GListData dynamicData = radio.listData();
        if(!dynamicData.enable()){
//            throw new DynamicDataNotSetException();
            throw new BaseGViewException(String.format("页面【%s】的 @GRadio 没有设 listData ",
                    context.getViewName()));
        }

        GListDataModel dataModel = initListData(context, dynamicData);
        radioModel.setListData(dataModel);

        return radioModel;
    }


    /**
     * 文件上传框初始化
     */
    private GFileModel initFile(GFile file) {
        GFileModel fileModel = new GFileModel();
        fileModel.setAccept(file.accept());
        fileModel.setShowIf(file.showIf());
        fileModel.setDisableIf(file.disableIf());
        fileModel.setKeyName(file.keyName());
        if(StringUtils.isEmpty(file.filenameKeyName())){
            fileModel.setFilenameKeyName("xxx_" + file.keyName());
        }else {
            fileModel.setFilenameKeyName(file.filenameKeyName());
        }
        fileModel.setLimit(file.limit());
        fileModel.setName(file.name());
        fileModel.setFileUploadType(file.fileUploadType());
        fileModel.setRequired(file.required());
        fileModel.setPlaceholder(file.placeholder());
        fileModel.setMaxSize(file.maxSize());
        return fileModel;
    }

    private GCheckBoxModel initCheckBox(GContext context, GCheckBox checkBox) {
        GCheckBoxModel checkBoxModel = new GCheckBoxModel();
        checkBoxModel.setName(checkBox.name());
        checkBoxModel.setKeyName(checkBox.keyName());
        checkBoxModel.setRequired(checkBox.required());
        checkBoxModel.setShowIf(checkBox.showIf());
        checkBoxModel.setDisableIf(checkBox.disableIf());
//        checkBoxModel.setOnChangeAction(checkBox.onChangeAction());
//        checkExistAction(context,  checkBox.onChangeAction());

        if(StringUtils.isNotEmpty(checkBox.onChangeAction())){
            checkBoxModel.setButtonId(IdUtils.nextButtonId(checkBox.onChangeAction()));
            // 设置对应的actionName
            String actionName = checkBox.onChangeAction();
            ActionPo action = coreService.findActionByName(actionName);
            if(action == null){
                throw new BaseGViewException(String.format("【%s】里面的设了onChangeAction=%s，但是没有找到对应的actionName"
                        , context.getViewName(), actionName));
//                        throw new ActionNotFoundException(context, actionName);
            }
            actionService.putConfirmAction(context, checkBoxModel.getButtonId(),
                    action.getActionService(), action.getActionMethod());
        }
        return checkBoxModel;
    }

    private GSwitchBoxModel initSwitch(GContext context, GSwitch gSwitch) {
        GSwitchBoxModel checkBoxModel = new GSwitchBoxModel();
        checkBoxModel.setName(gSwitch.name());
        checkBoxModel.setKeyName(gSwitch.keyName());
        checkBoxModel.setRequired(gSwitch.required());
        checkBoxModel.setShowIf(gSwitch.showIf());
        checkBoxModel.setDisableIf(gSwitch.disableIf());
//        checkBoxModel.setOnChangeAction(gSwitch.onChangeAction());
//        checkExistAction(context,  gSwitch.onChangeAction());

        // 2024/06/24 新增，用于判断按钮的权限确定是否显示
        if(gSwitch.permission() != null && gSwitch.permission().length > 0){
            if(permissionHandler != null){
                if(!permissionHandler.handPermissions(context, gSwitch.permission(), checkBoxModel)){
                    return null;
                }
            }
        }

        if(StringUtils.isNotEmpty(gSwitch.onChangeAction())){
            checkBoxModel.setButtonId(IdUtils.nextButtonId(gSwitch.onChangeAction()));
            // 设置对应的actionName
            String actionName = gSwitch.onChangeAction();
            ActionPo action = coreService.findActionByName(actionName);
            if(action == null){
                throw new BaseGViewException(String.format("【%s】里面的设了onChangeAction=%s，但是没有找到对应的actionName"
                        , context.getViewName(), actionName));
//                        throw new ActionNotFoundException(context, actionName);
            }
            actionService.putConfirmAction(context, checkBoxModel.getButtonId(),
                    action.getActionService(), action.getActionMethod());
        }
        return checkBoxModel;
    }

    private GMultiTreeSelectorModel initMultiTreeSelector(GContext context, GMultiTreeSelector selector) {
        GMultiTreeSelectorModel selectorModel = new GMultiTreeSelectorModel();
        selectorModel.setName(selector.name());
        selectorModel.setItemType("multi_tree_selector");
        selectorModel.setKeyName(selector.keyName());
        selectorModel.setRequired(selector.required());
        selectorModel.setShowIf(selector.showIf());
        selectorModel.setDisableIf(selector.disableIf());
//        selectorModel.setOnChangeAction(selector.onChangeAction());
        checkExistAction(context,  selector.onChangeAction());

        if(StringUtils.isNotEmpty(selector.onChangeAction())){
            selectorModel.setButtonId(IdUtils.nextButtonId(selector.onChangeAction()));
            // 设置对应的actionName
            String actionName = selector.onChangeAction();
            ActionPo action = coreService.findActionByName(actionName);
            if(action == null){
                throw new BaseGViewException(String.format("【%s】里面的设了onChangeAction=%s，但是没有找到对应的actionName"
                        , context.getViewName(), actionName));
//                        throw new ActionNotFoundException(context, actionName);
            }
            actionService.putConfirmAction(context, selectorModel.getButtonId(),
                    action.getActionService(), action.getActionMethod());
        }
        GTreeData treeData = selector.treeData();
        if(!treeData.enable()){
//            throw new DynamicDataNotSetException();
            throw new BaseGViewException(String.format("页面【%s】的 @MultiTreeSelector 没有设 treeData ",
                    context.getViewName()));
        }

        GTreeDataModel dataModel = initTreeSelectorData(context, treeData);
        selectorModel.setTreeData(dataModel);

        return selectorModel;
    }

    /**
     * 初始化多选下拉框
     */
    private GMultiSelectorModel initMultiSelector(GContext context, GMultiSelector selector) {
        GMultiSelectorModel selectorModel = new GMultiSelectorModel();
        selectorModel.setName(selector.name());
        selectorModel.setItemType("multi_selector");
        selectorModel.setKeyName(selector.keyName());
        selectorModel.setRequired(selector.required());
        selectorModel.setShowIf(selector.showIf());
        selectorModel.setDisableIf(selector.disableIf());
        checkExistAction(context,  selector.onChangeAction());

//        if(selector.dataSource() == DataSource.STATIC){
//            String[] keyValue = selector.staticData();
//            if(keyValue == null){
//                throw new StaticNotFoundException(context.getBoardClass());
//            }
//
//            selectorModel.setValues(new ArrayList<>());
//            for(String kv : keyValue){
//                String[] kvs = kv.split("=");
//                if(kvs == null || kvs.length != 2){
//                    throw new StaticValueFormatException();
//                }
//                selectorModel.getValues().add(new KeyValue(kvs[0], kvs[1]));
//            }
//        } else if(selector.dataSource() == DataSource.DYNAMIC){

        GListData dynamicData = selector.listData();
        if(!dynamicData.enable()){
//                throw new DynamicDataNotSetException();
            throw new BaseGViewException(String.format("页面【%s】的 @GMultiSelector 没有设 listData ",
                    context.getViewName()));
        }

        GListDataModel dataModel = initListData(context, dynamicData);
        selectorModel.setListData(dataModel);


        if(StringUtils.isNotEmpty(selector.onChangeAction())){
            selectorModel.setButtonId(IdUtils.nextButtonId(selector.onChangeAction()));
            // 设置对应的actionName
            String actionName = selector.onChangeAction();
            ActionPo action = coreService.findActionByName(actionName);
            if(action == null){
                throw new BaseGViewException(String.format("【%s】里面的设了onChangeAction=%s，但是没有找到对应的actionName"
                        , context.getViewName(), actionName));
//                        throw new ActionNotFoundException(context, actionName);
            }
            actionService.putConfirmAction(context, selectorModel.getButtonId(),
                    action.getActionService(), action.getActionMethod());
        }
        return selectorModel;
    }


    /***
     * 检查action是否有效
     * @param context
     * @param actionName
     */
    private void checkExistAction(GContext context, String actionName) {
        if(StringUtils.isEmpty(actionName)){
            return;
        }
         ActionPo action = coreService.findActionByName(actionName);
        if(action == null){
            throw new BaseGViewException(String.format("【%s】里面没有找到对应的actionName【%s】"
                    , context.getViewName(), actionName));
//                        throw new ActionNotFoundException(context, actionName);
        }
    }


    private GSelectorModel initSelector(GContext context, GSelector selector) {
        GSelectorModel selectorModel = new GSelectorModel();
        selectorModel.setName(selector.name());
        selectorModel.setKeyName(selector.keyName());
        selectorModel.setRequired(selector.required());
        selectorModel.setShowIf(selector.showIf());
        selectorModel.setDisableIf(selector.disableIf());
//        selectorModel.setOnChangeAction(selector.onChangeAction());
        checkExistAction(context,  selector.onChangeAction());

        GListData listData = selector.listData();
        if(!listData.enable()){
//            throw new DynamicDataNotSetException();
            throw new BaseGViewException(String.format("页面【%s】的 @Selector 没有设 listData ",
                    context.getViewName()));
        }

        GListDataModel dataModel = initListData(context, listData);
        selectorModel.setListData(dataModel);
//        }
        if(StringUtils.isNotEmpty(selector.onChangeAction())){
            selectorModel.setButtonId(IdUtils.nextButtonId(selector.onChangeAction()));
            // 设置对应的actionName
            String actionName = selector.onChangeAction();
            ActionPo action = coreService.findActionByName(actionName);
            if(action == null){
                throw new BaseGViewException(String.format("【%s】里面的设了onChangeAction=%s，但是没有找到对应的actionName"
                        , context.getViewName(), actionName));
//                        throw new ActionNotFoundException(context, actionName);
            }
            actionService.putConfirmAction(context, selectorModel.getButtonId(),
                    action.getActionService(), action.getActionMethod());
        }
        return selectorModel;
    }


    /**
     * 初始化页面数据
     */
    private GTableDataModel initTableData(GContext context, GTableData data) {
        GTableDataModel dataModel = new GTableDataModel();
        if(StringUtils.isEmpty(data.keyName())){
            throw new BaseGViewException(String.format("页面【%s】的 @GTableData 没有设 keyName"));
        }
        dataModel.setKeyName(data.keyName());

        if(StringUtils.isNotEmpty(data.fromTableDataPickerClassName())){
            String dataId = StringUtils.isEmpty(data.dataId()) ? IdUtils.nextDataId() : data.dataId();
            dataModel.setDataId(dataId);
            try {
                Class<? extends ITableDataPicker> clazz =
                        (Class<? extends ITableDataPicker>) ClassUtils.getClass(data.fromTableDataPickerClassName());
                dataService.readyTableData(context, dataId, clazz);
            } catch (Exception ex) {
//                throw new DynamicClassNotFoundException(data.fromTableDataPickerClassName());
                throw new BaseGViewException(String.format("页面【%s】的 @GTableData 没有设 找不到【%s】", context.getViewName(),
                        data.fromTableDataPickerClassName()));
            }
        } else if(!data.fromTableDataPicker().equals(EmptyTableDataPicker.class)){
            String dataId = StringUtils.isEmpty(data.dataId()) ? IdUtils.nextDataId() : data.dataId();
            dataModel.setDataId(dataId);
            dataService.readyTableData(context, dataId, data.fromTableDataPicker());
        } else if(StringUtils.isNotEmpty(data.fromDataSource())){
            String dataId = StringUtils.isEmpty(data.dataId()) ? IdUtils.nextDataId(data.fromDataSource()) : data.dataId();
            dataModel.setDataId(dataId);
            String dataSource = data.fromDataSource();
            DataSourcePo source = coreService.findDataSourceByName(dataSource);
            if(source == null){
                throw new BaseGViewException(String.format("【%s】里面的某个@GTableData没有找到对应的dataSource【%s】"
                        , context.getViewName(), data.fromDataSource()));
//                        throw new ActionNotFoundException(context, actionName);
            }

            // TODO 校验方法的返回内容是否有该keyName
//            GViewUtils.validateKeyNameForTableData(data.keyName(), source.getSourceMethod());
            dataService.readyTableDataSource(context, dataId,
                    source.getSourceService(), source.getSourceMethod(), dataSource);


            // TODO 校验keyName是否合法

//            dataService.readyTableData(context, dataId, data.fromTableDataPicker());
        } else {
            throw new BaseGViewException(String.format("页面【%s】的 @GTableData 没有设置任何一样数据源", context.getViewName()));
        }
        return dataModel;
    }


    /**
     * 初始化下拉数据
     */
    private GSimpleListDataModel initSimpleListData(GContext context, GSimpleListData listData) {
        GSimpleListDataModel dataModel = new GSimpleListDataModel();
//        String dataId = RandomStringUtils.random(32, true, true);
//        dataModel.setKeyName(listData.keyName());
//        dataModel.setValueName(listData.valueName());

//        if(StringUtils.isEmpty(dataModel.getValueName())){
//            throw new BaseGViewException(String.format("【%s】中@GListData必须添加value值", context.getViewName()));
//        }
//
//        if(StringUtils.isEmpty(dataModel.getKeyName())){
//            throw new BaseGViewException(String.format("【%s】中@GListData必须添加key值", context.getViewName()));
//        }

        if(StringUtils.isNotEmpty(listData.fromSql())){
            String sql = listData.fromSql();
            String dataId = StringUtils.isEmpty(listData.dataId()) ? IdUtils.nextDataId() : listData.dataId();
            dataModel.setDataId(dataId);
            dataService.readySqlData(context, dataId, sql);
        } else if(StringUtils.isNotEmpty(listData.fromListDataPickerClassName())){
            String dataId = StringUtils.isEmpty(listData.dataId()) ? IdUtils.nextDataId() : listData.dataId();
            dataModel.setDataId(dataId);
            try {
                Class<? extends IDataPicker> clazz =
                        (Class<? extends IDataPicker>) ClassUtils.getClass(listData.fromListDataPickerClassName());
                dataService.readyData(context, dataId, clazz);
            } catch (Exception ex) {
                throw new BaseGViewException(String.format("页面【%s】的 @GSimpleListData 找不到类【】 ",
                        context.getViewName(), listData.fromListDataPickerClassName()));
//                throw new DynamicClassNotFoundException(dynamicData.fromListDataPickerClassName());
            }
        } else if(!listData.fromListDataPicker().equals(EmptyListDataPicker.class)){
            String dataId = StringUtils.isEmpty(listData.dataId()) ? IdUtils.nextDataId() : listData.dataId();
            dataModel.setDataId(dataId);
            dataService.readyListData(context, dataId, listData.fromListDataPicker());
        } else if(StringUtils.isNotEmpty(listData.fromJson())){
            String dataId = StringUtils.isEmpty(listData.dataId()) ? IdUtils.nextDataId() : listData.dataId();
            dataModel.setDataId(dataId);
            String json = listData.fromJson().trim();
            if(!json.startsWith("[")){
//                throw new DynamicJsonDataFormatException(json);
                throw new BaseGViewException(String.format("页面【%s】的 @GListData 的json结构不对，json内容为【%s】 ",
                        context.getViewName(), json));
            }

//            String titleName = listData.titleName();
//            if(StringUtils.isNotEmpty(titleName)){
//                titleName = treeData.keyName();
//            }
            dataService.readyJsonData(context, dataId, listData.fromJson(), null);
        } else if(StringUtils.isNotEmpty(listData.fromDataSource())){
            String dataId = StringUtils.isEmpty(listData.dataId()) ? IdUtils.nextDataId(listData.fromDataSource()) : listData.dataId();
            dataModel.setDataId(dataId);
            String dataSource = listData.fromDataSource();
            DataSourcePo source = coreService.findDataSourceByName(dataSource);
            if(source == null){
                throw new BaseGViewException(String.format("【%s】里面的某个@GListData没有找到对应的dataSource【%s】"
                        , context.getViewName(), listData.fromDataSource()));
//                        throw new ActionNotFoundException(context, actionName);
            }
            dataService.readyListDataSource(context, dataId,
                    source.getSourceService(), source.getSourceMethod(), dataSource);
        } else {
            throw new BaseGViewException(String.format("页面【%s】的 @GListData 没有设置任何一样数据源", context.getViewName()));
        }
        return dataModel;
    }



    /**
     * 初始化下拉数据
     */
    private GListDataModel initListData(GContext context, GListData listData) {
        GListDataModel dataModel = new GListDataModel();
        dataModel.setKeyName(listData.keyName());
        if("".equals(listData.titleName())){
            dataModel.setTitleName(listData.keyName());
        } else {
            dataModel.setTitleName(listData.titleName());
        }
        dataModel.setValueName(listData.valueName());

        if(StringUtils.isNotEmpty(listData.fromEnums())){
            String dataId = StringUtils.isEmpty(listData.dataId()) ? IdUtils.nextDataId() : listData.dataId();
            dataModel.setDataId(dataId);
            String enumName = listData.fromEnums();
            dataService.readyEnumsData(context, dataId, enumName);
            dataModel.setKeyName("key");
            dataModel.setValueName("value");
            dataModel.setTitleName("title");
            return dataModel;
        }


        if(StringUtils.isEmpty(dataModel.getValueName())){
            throw new BaseGViewException(String.format("【%s】中@GListData必须添加value值", context.getViewName()));
        }

        if(StringUtils.isEmpty(dataModel.getKeyName())){
            throw new BaseGViewException(String.format("【%s】中@GListData必须添加key值", context.getViewName()));
        }

        if(StringUtils.isNotEmpty(listData.fromSql())){
            String dataId = StringUtils.isEmpty(listData.dataId()) ? IdUtils.nextDataId() : listData.dataId();
            dataModel.setDataId(dataId);
            String sql = listData.fromSql();
            dataService.readySqlData(context, dataId, sql);
        } else if(StringUtils.isNotEmpty(listData.fromListDataPickerClassName())){
            String dataId = StringUtils.isEmpty(listData.dataId()) ? IdUtils.nextDataId() : listData.dataId();
            dataModel.setDataId(dataId);
            try {
                Class<? extends IListDataPicker> clazz =
                        (Class<? extends IListDataPicker>) ClassUtils.getClass(listData.fromListDataPickerClassName());
                dataService.readyListData(context, dataId, clazz);
            } catch (Exception ex) {
                throw new BaseGViewException(String.format("页面【%s】的 @GListData 找不到类【%s】 ",
                        context.getViewName(), listData.fromListDataPickerClassName()));
//                throw new DynamicClassNotFoundException(dynamicData.fromListDataPickerClassName());
            }
        } else if(!listData.fromListDataPicker().equals(EmptyListDataPicker.class)){
            String dataId = StringUtils.isEmpty(listData.dataId()) ? IdUtils.nextDataId() : listData.dataId();
            dataModel.setDataId(dataId);
            dataService.readyListData(context, dataId, listData.fromListDataPicker());
        } else if(StringUtils.isNotEmpty(listData.fromJson())){
            String dataId = StringUtils.isEmpty(listData.dataId()) ? IdUtils.nextDataId() : listData.dataId();
            dataModel.setDataId(dataId);
            String json = listData.fromJson().trim();
            if(!json.startsWith("[")){
//                throw new DynamicJsonDataFormatException(json);
                throw new BaseGViewException(String.format("页面【%s】的 @GListData 的json结构不对 ",
                        context.getViewName()));
            }


//            if(StringUtils.isNotEmpty(listData.keyName())){
//                GViewUtils.validateKeyNameForListDataJson(listData.keyName(), json);
//            }

            String titleName = listData.titleName();
            if(StringUtils.isEmpty(titleName)){
                titleName = listData.keyName();
            }
            dataService.readyJsonData(context, dataId, listData.fromJson(), titleName);
        } else if(StringUtils.isNotEmpty(listData.fromDataSource())){
            String dataId = StringUtils.isEmpty(listData.dataId()) ? IdUtils.nextDataId() : listData.dataId();
            dataModel.setDataId(dataId);
            String dataSource = listData.fromDataSource();
            DataSourcePo source = coreService.findDataSourceByName(dataSource);
            if(source == null){
                throw new BaseGViewException(String.format("【%s】里面的某个@GListData没有找到对应的dataSource【%s】"
                        , context.getViewName(), listData.fromDataSource()));
//                        throw new ActionNotFoundException(context, actionName);
            }
//            if(StringUtils.isNotEmpty(listData.keyName())){
//                GViewUtils.validateKeyNameForListData(listData.keyName(), source.getSourceMethod());
//            }
            dataService.readyListDataSource(context, dataId,
                    source.getSourceService(), source.getSourceMethod(), dataSource);
        } else {
            throw new BaseGViewException(String.format("页面【%s】的 @GListData 没有设置任何一样数据源", context.getViewName()));
        }
        return dataModel;
    }



    /**
     * 初始化单对象的数据
     */
    private GDataModel initData(GContext context, GData data) {
        GDataModel dataModel = new GDataModel();
        String dataId = StringUtils.isEmpty(data.dataId()) ? IdUtils.nextDataId() : data.dataId();
        dataModel.setDataId(dataId);
//        dataModel.setKeyName(data.keyName());
//        dataModel.setValueName(data.valueName());


        if(StringUtils.isNotEmpty(data.fromSql())){
            String sql = data.fromSql();
            dataService.readySingleSqlData(context, dataId, sql);
        } else if(StringUtils.isNotEmpty(data.fromDataPickerClassName())){
            try {
                Class<? extends IDataPicker> clazz =
                        (Class<? extends IDataPicker>) ClassUtils.getClass(data.fromDataPickerClassName());
                dataService.readyData(context, dataId, clazz);
            } catch (Exception ex) {
                throw new BaseGViewException(String.format("页面【%s】的 @GData 找不到类【%s】 ",
                        context.getViewName(), data.fromDataPickerClassName()));
//                throw new DynamicClassNotFoundException(dynamicData.fromListDataPickerClassName());
            }
        } else if(!data.fromDataPicker().equals(EmptyDataPicker.class)){
            dataService.readyData(context, dataId, data.fromDataPicker());
        } else if(StringUtils.isNotEmpty(data.fromJson())){
            String json = data.fromJson().trim();
            if(!json.startsWith("{")){
//                throw new DynamicJsonDataFormatException(json);
                throw new BaseGViewException(String.format("页面【%s】的 @GData 的json结构不对 ",
                        context.getViewName()));
            }

//            String titleName = listData.titleName();
//            if(StringUtils.isNotEmpty(titleName)){
//                titleName = listData.keyName();
//            }
            dataService.readyJsonData(context, dataId, data.fromJson(), null);
        } else if(StringUtils.isNotEmpty(data.fromDataSource())){
            String dataSource = data.fromDataSource();
            DataSourcePo source = coreService.findDataSourceByName(dataSource);
            if(source == null){
                throw new BaseGViewException(String.format("【%s】里面的某个@GData没有找到对应的dataSource【%s】"
                        , context.getViewName(), data.fromDataSource()));
//                        throw new ActionNotFoundException(context, actionName);
            }
            dataService.readySingleDataSource(context, dataId,
                    source.getSourceService(), source.getSourceMethod(), dataSource);
        } else {
            throw new BaseGViewException(String.format("页面【%s】的 @GData 没有设置任何一样数据源", context.getViewName()));
        }
        return dataModel;
    }


    /**
     * 初始化下拉的树状数据
     * @return
     */
    private GTreeDataModel initTreeSelectorData(GContext context, GTreeData treeData) {
        GTreeDataModel dataModel = new GTreeDataModel();
        dataModel.setKeyName(treeData.keyName());
        dataModel.setValueName(treeData.valueName());
        if("".equals(treeData.titleName())){
            dataModel.setTitleName(treeData.keyName());
        } else {
            dataModel.setTitleName(treeData.titleName());
        }
        dataModel.setParentKeyName(treeData.parentKeyName());


        if(StringUtils.isNotEmpty(treeData.fromEnums())){
            String dataId = StringUtils.isEmpty(treeData.dataId()) ? IdUtils.nextDataId() : treeData.dataId();
            dataModel.setDataId(dataId);
            String enumName = treeData.fromEnums();
            dataService.readyEnumsData(context, dataId, enumName);
            dataModel.setKeyName("key");
            dataModel.setValueName("value");
            dataModel.setTitleName("title");
            dataModel.setParentKeyName("parentKey");
            return dataModel;
        }

        if(StringUtils.isNotEmpty(treeData.fromSql())){
            String dataId = StringUtils.isEmpty(treeData.dataId()) ? IdUtils.nextDataId() : treeData.dataId();
            dataModel.setDataId(dataId);
            String sql = treeData.fromSql();
            dataService.readySqlData(context, dataId, sql);
        } else if(StringUtils.isNotEmpty(treeData.fromListDataPickerClassName())){
            String dataId = StringUtils.isEmpty(treeData.dataId()) ? IdUtils.nextDataId() : treeData.dataId();
            dataModel.setDataId(dataId);
            try {
                Class<? extends IListDataPicker> clazz =
                        (Class<? extends IListDataPicker>) ClassUtils.getClass(treeData.fromListDataPickerClassName());
                dataService.readyListData(context, dataId, clazz);
            } catch (Exception ex) {
                throw new BaseGViewException(String.format("页面【%s】的 @GTreeData 没有设 treeData，找不到类【%s】 ",
                        context.getViewName(), treeData.fromListDataPickerClassName()));
            }
        } else if(!treeData.fromListDataPicker().equals(EmptyListDataPicker.class)){
            String dataId = StringUtils.isEmpty(treeData.dataId()) ? IdUtils.nextDataId() : treeData.dataId();
            dataModel.setDataId(dataId);
            dataService.readyListData(context, dataId, treeData.fromListDataPicker());
        } else if(StringUtils.isNotEmpty(treeData.fromJson())){
            String json = treeData.fromJson().trim();
            String dataId = StringUtils.isEmpty(treeData.dataId()) ? IdUtils.nextDataId() : treeData.dataId();
            dataModel.setDataId(dataId);
            if(!json.startsWith("[")){
                throw new BaseGViewException(String.format("页面【%s】的 @GTreeData 的json有问题 ",
                        context.getViewName()));
            }

            String titleName = treeData.titleName();
            if(StringUtils.isEmpty(titleName)){
                titleName = treeData.keyName();
            }
            dataService.readyJsonData(context, dataId, treeData.fromJson(), titleName);
        } else if(StringUtils.isNotEmpty(treeData.fromDataSource())){
            String dataSource = treeData.fromDataSource();
            DataSourcePo source = coreService.findDataSourceByName(dataSource);
            String dataId = StringUtils.isEmpty(treeData.dataId()) ? IdUtils.nextDataId(treeData.fromDataSource()) : treeData.dataId();
            dataModel.setDataId(dataId);
            if(source == null){
                throw new BaseGViewException(String.format("【%s】里面的某个@GTreeData没有找到对应的dataSource【%s】"
                        , context.getViewName(), treeData.fromDataSource()));
//                        throw new ActionNotFoundException(context, actionName);
            }
            dataService.readyListDataSource(context, dataId,
                    source.getSourceService(), source.getSourceMethod(), dataSource);
        } else {
            throw new BaseGViewException(String.format("页面【%s】的 @GTreeData 没有设置任何一样数据源", context.getViewName()));
        }
        return dataModel;
    }

    private GHiddenModel initHidden(GHidden hidden) {
        GHiddenModel hiddenModel = new GHiddenModel();
        hiddenModel.setKeyName(hidden.keyName());
        hiddenModel.setValueName(hidden.valueName());
        return hiddenModel;
    }

    private List<String> initBoardName(Class<?> clazz) {
        List<String> result = new ArrayList<>();

        GView board = clazz.getAnnotation(GView.class);

        if(board == null){
            GViews boards = clazz.getAnnotation(GViews.class);
            for(GView b : boards.value()){
                if(result.contains(b.viewName())){
//                    throw new BoardRepeatException(board.viewName());
                    throw new BaseGViewException(String.format("找到2个重复的view名字【%s】",
                            board.viewName()));
                }
                result.add(b.viewName());
            }
        } else {
            if(result.contains(board.viewName())){
//                throw new BoardRepeatException(board.viewName());
                throw new BaseGViewException(String.format("找到2个重复的view名字【%s】",
                        board.viewName()));
            }
            result.add(board.viewName());
        }
        return result;
    }


}
